<template>
  <ContentWrap>
    <!-- 搜索表单 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="班级名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入班级名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option label="正常" :value="0" />
          <el-option label="禁用" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['miniprogram:class:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="班级ID" align="center" prop="id" />
      <el-table-column label="班级名称" align="center" prop="name" />
      <el-table-column label="班级描述" align="center" prop="description" show-overflow-tooltip />
      <el-table-column label="成员数量" align="center" prop="memberCount" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
            {{ scope.row.status === 0 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ formatDate(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openMembers(scope.row)"
            v-hasPermi="['miniprogram:class:query']"
          >
            成员管理
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row)"
            v-hasPermi="['miniprogram:class:update']"
          >
            修改
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['miniprogram:class:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ClassForm ref="formRef" @success="getList" />

  <!-- 成员管理对话框 -->
  <el-dialog v-model="membersVisible" title="成员管理" width="1000px" append-to-body>
    <div class="mb-4">
      <el-button type="primary" @click="openAddMember">
        <Icon icon="ep:plus" class="mr-5px" /> 添加成员
      </el-button>
    </div>
    <el-table v-loading="membersLoading" :data="membersList" :stripe="true">
      <el-table-column label="用户ID" align="center" prop="userId" />
      <el-table-column label="用户昵称" align="center" prop="nickname" />
      <el-table-column label="手机号" align="center" prop="mobile" />
      <el-table-column label="加入时间" align="center" prop="joinTime" width="180">
        <template #default="scope">
          <span>{{ formatDate(scope.row.joinTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120">
        <template #default="scope">
          <el-button
            link
            type="danger"
            @click="handleRemoveMember(scope.row.userId)"
          >
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="membersTotal"
      v-model:page="membersQueryParams.pageNo"
      v-model:limit="membersQueryParams.pageSize"
      @pagination="getMembersList"
    />
    <template #footer>
      <el-button @click="membersVisible = false">关闭</el-button>
    </template>
  </el-dialog>

  <!-- 添加成员对话框 -->
  <el-dialog v-model="addMemberVisible" title="添加成员" width="600px" append-to-body>
    <el-form :model="addMemberForm" ref="addMemberFormRef" label-width="80px">
      <el-form-item label="用户ID" prop="userId" :rules="[{ required: true, message: '请输入用户ID', trigger: 'blur' }]">
        <el-input v-model.number="addMemberForm.userId" placeholder="请输入用户ID" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="addMemberVisible = false">取消</el-button>
      <el-button type="primary" @click="handleAddMember">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { formatDate } from '@/utils/formatTime'
import * as ClassApi from '@/api/miniprogram/class'
import ClassForm from './ClassForm.vue'

defineOptions({ name: 'MiniProgramClass' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  status: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const formRef = ref() // 表单 Ref

// 成员管理相关
const membersVisible = ref(false)
const membersLoading = ref(false)
const membersList = ref([])
const membersTotal = ref(0)
const currentClassId = ref(0)
const membersQueryParams = reactive({
  pageNo: 1,
  pageSize: 10
})

// 添加成员相关
const addMemberVisible = ref(false)
const addMemberForm = reactive({
  userId: undefined
})
const addMemberFormRef = ref()

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ClassApi.getClassPage(queryParams)
    list.value = data.records || data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const openForm = (type: string, row?: any) => {
  formRef.value.open(type, row?.id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ClassApi.deleteClass(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 成员管理 */
const openMembers = (row: any) => {
  currentClassId.value = row.id
  membersQueryParams.pageNo = 1
  getMembersList()
  membersVisible.value = true
}

/** 获取成员列表 */
const getMembersList = async () => {
  membersLoading.value = true
  try {
    const data = await ClassApi.getClassMembers(currentClassId.value, membersQueryParams)
    membersList.value = data.records || data.list
    membersTotal.value = data.total
  } finally {
    membersLoading.value = false
  }
}

/** 添加成员 */
const openAddMember = () => {
  addMemberForm.userId = undefined
  addMemberVisible.value = true
}

/** 确认添加成员 */
const handleAddMember = async () => {
  try {
    await addMemberFormRef.value.validate()
    await ClassApi.addClassMember(currentClassId.value, addMemberForm.userId)
    message.success('添加成员成功')
    addMemberVisible.value = false
    await getMembersList()
  } catch {}
}

/** 移除成员 */
const handleRemoveMember = async (userId: number) => {
  try {
    await message.confirm('确认要移除该成员吗？')
    await ClassApi.removeClassMember(currentClassId.value, userId)
    message.success('移除成员成功')
    await getMembersList()
  } catch {}
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>